import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {Form, Button, Card,Radio,Select,DatePicker,Upload,Icon,Input} from 'antd';
import {message} from "antd/lib/index";
import constants from '../../../common/constants';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
import moment from 'moment';
const { RangePicker } = DatePicker;

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

@connect(state => ({
    submitting: state.recObject.loading,
}))
@Form.create()
export default class RecObjectAdd extends PureComponent {

    state = {
        urlData: [],
        seatData: [],
        start_time: this.props.record.start_time || '',
        end_time: this.props.record.end_time || '',
        obj_type:this.props.type,
    }

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({
            type: 'adAddress/queryAllYyDetailUrl',
            callback: (response) => {
                if (response.result === 0) {
                    this.setState({
                        urlData: response.resultData.yyDetailUrlList,
                    });
                }
                else{
                    message.success('失败');
                }
            }
        })
        dispatch({
            type: 'adConfigruation/queryAllAdConfigruation',
            callback: (response) => {
                if (response.result === 0) {
                    this.setState({
                        seatData: response.resultData.adConfigruationList,
                    });
                }
                else{
                    message.success('失败');
                }
            }
        })
    }

    handleParentModalVisible = (e) => {
        this.props.handlerecObjectVisible();
    }

    handleSubmit = (editType,priority_id, obj_id, e) => {
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                let user_id = '';
                const userInfoState = sessionStorage.getItem("userInfoState");
                if(userInfoState !==null){
                    const {userInfo} = JSON.parse(userInfoState);
                    user_id = userInfo.user_id;
                }
                if (user_id != ''){
                    this.props.dispatch({
                        type: `recObjectEdit/${editType}`,
                        payload: {...values,
                            priority_id: priority_id,
                            user_id: user_id,
                            obj_id:obj_id,
                            start_time:this.state.start_time,
                            end_time:this.state.end_time,
                            obj_type:this.state.obj_type,
                        },
                        callback: (response) => {
                            if (response.result === 0) {
                                message.success('提交成功');
                                this.props.handlerecObjectVisible();
                                if (editType === 'mod'){
                                    this.props.handleModalSuccess(this.props.pagination);
                                }else {
                                    this.props.returnRecObject();
                                }
                            } else {
                                message.success('提交失败');
                            }
                        }
                    });
                }
            }
        });
    }

    onDateChange = (value, dateString) => {
        this.setState({
            start_time: dateString[0],
            end_time: dateString[1]
        })
    }

    handleChange = (info) => {
        if (info.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj, imageUrl => this.setState({
                imageUrl,
                loading: false,
            }));
        }
    }

    normFile = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && `${e.file.response[0].fileUrl}`;
    }

    render() {
        const urlOptions = this.state.urlData.map(d => <Option value={d.value}>{d.label}</Option>);
        const seatOptions = this.state.seatData.map(d => <Option value={d.value}>{d.label}</Option>);
        const {submitting, record, editType, recObjectList,type} = this.props;
        const {getFieldDecorator, getFieldValue} = this.props.form;
        const formInitValue = editType === 'add' ? '' : record;
        const priority_id = editType === 'add' ? '' : record.priority_id;
        const obj_id = editType === 'add' ? (type === 1 ? record.goods_id : type ===2?record.brand_id:record.cat_id) : record.obj_id;
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 7},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 12},
                md: {span: 10},
            },
        };
        const submitFormLayout = {
            wrapperCol: {
                xs: {span: 24, offset: 0},
                sm: {span: 10, offset: 7},
            },
        };
        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">上传</div>
            </div>
        );

        const imageUrl = this.state.imageUrl;
        return (
            <Card bordered={false}>
                <Form
                    onSubmit={this.handleSubmit}
                    hideRequiredMark
                >
                    <FormItem
                        {...formItemLayout}
                        label="广告推荐位置"
                    >
                        {getFieldDecorator('seat_id', {
                            initialValue:  formInitValue.seat_id || '',
                            rules: [{
                                required: true, message: '请选择广告推荐的位置',
                            }
                            ],
                        })(
                            <Select placeholder="请选择" style={{width: '100%'}}>
                                {seatOptions}
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="广告推荐转入地址详情"
                    >
                        {getFieldDecorator('du_id', {
                            initialValue:  formInitValue.du_id || '',
                            rules: [{
                                required: true, message: '请选择广告推荐转入地址',
                            }
                            ],
                        })(
                            <Select placeholder="请选择" style={{width: '100%'}}>
                                {urlOptions}
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="状态"
                    >
                        {getFieldDecorator('status', {
                            initialValue:  !formInitValue.status ? 0 : 1,
                            rules: [{
                                required: true, message: '请选择',
                            }],
                        })(
                            <RadioGroup>
                                <Radio value={1}>在用</Radio>
                                <Radio value={0}>不在用</Radio>
                            </RadioGroup>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="生效时间"
                    >
                        {getFieldDecorator('promote_date', {
                             initialValue: this.props.editType === 'mod' ? [moment(this.state.start_time, 'YYYY-MM-DD HH:mm:ss'),
                                 moment(this.state.end_time, 'YYYY-MM-DD HH:mm:ss')] : [],
                            rules: [{
                                required: true, message: '请选择生效时间',
                            }],
                        })(
                            <RangePicker
                                showTime format="YYYY-MM-DD HH:mm:ss" onChange={this.onDateChange}/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="推荐标题"
                    >
                        {getFieldDecorator('obj_title', {
                            initialValue:  formInitValue.obj_title || '',
                            rules: [{
                                required: true, message: '请输入推荐标题',
                            }],
                        })(
                            <Input placeholder="推荐标题"/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="推荐图片"
                    >
                        {getFieldDecorator('obj_img', {
                            initialValue:  formInitValue.obj_img || '',
                            getValueFromEvent: this.normFile,
                            rules: [{
                                required: true, message: '请上传图片',
                            }],
                        })(
                            <Upload
                                name="avatar"
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action={constants.fileServer}
                                onChange={this.handleChange}
                            >
                                {
                                    !imageUrl ?
                                        formInitValue.obj_img ? <img src={`${constants.imageUrlFix}${formInitValue.obj_img}`} alt="" /> : uploadButton
                                        : <img src={imageUrl} alt="" />
                                }

                            </Upload>
                        )}
                    </FormItem>

                    <FormItem {...submitFormLayout} style={{marginTop: 32}}>
                        <Button type="primary" loading={submitting} onClick={this.handleSubmit.bind(this,editType,priority_id,obj_id)}>
                            提交
                        </Button>
                        <Button style={{marginLeft: 8}} onClick={this.handleParentModalVisible}>取消</Button>
                    </FormItem>
                </Form>
            </Card>
        );
    }
}
